package com.aaa.api;




import com.aaa.config.OSSClientUtil;
import com.aaa.controller.HttpUtils;
import com.aaa.mapper.TabMenuMapper;
import com.aaa.mapper.TabRoleMapper;
import com.aaa.mapper.TabUserMapper;
import com.aaa.service.impl.TGuestServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.comm.entity.TGuest;
import com.comm.entity.TabMenu;
import com.comm.entity.TabRole;
import com.comm.entity.TabUser;

import com.comm.util.Result;
import io.lettuce.core.ScriptOutputType;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.io.File;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController

@RequestMapping("userApi")
public class UserApiController {
    @Autowired
    private OSSClientUtil ossClientUtil;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
private TabUserMapper userMapper;

    @Resource
    private TabRoleMapper roleMapper;

    @Resource
    private TabMenuMapper menuMapper;
    @Resource
    private TGuestServiceImpl tGuestService;

    /**
     * 根据客户的电话查询客户的信息
     * @return
     */
    @PostMapping("getguest/{phone}")
    public TGuest selectByName(@PathVariable String phone){
        System.out.println("进入查找guest");
        System.out.println(tGuestService.selectByPhone(phone));
        return tGuestService.selectByPhone(phone);
    }

    /**
     * 修改用户信息
     * @param tGuest
     * @return
     */
    @PostMapping("/updateguest")
    public boolean updateGuest(@RequestBody TGuest tGuest){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dateFormat.format(date));
        Instant instant = date.toInstant();
        LocalDate ld = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        tGuest.setUpdatetime(ld);
        System.out.println(tGuest);
        return tGuestService.updateById(tGuest);
    }
    /**
     * 根据用户的名字查询用户的信息
     * @return
     */
    @PostMapping("getuser/{name}")
    public TabUser getUserByName(@PathVariable String name) {
        //
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",name);// username="1222"
        TabUser one = userMapper.selectOne(queryWrapper);
        return one;

    }
    /**
     * 根据用户的id  查询用户的角色信息
     */
    @PostMapping("getrole/{uid}")
    public List<TabRole> getRoleByUid(@PathVariable Integer uid){
        // 调用
        List<TabRole> roleList = roleMapper.getRoleByUid(uid);
        return roleList;
    }

    /**
     * 根据用户的id 查询用户的资源的信息
     */
    @PostMapping("getmenus/{rids}")
    public  List<TabMenu> getMenusByUid(@PathVariable List<Integer> rids){
        List<TabMenu> menuList = menuMapper.getMenusByRids(rids);
        return menuList;
    }

    /**
     * 手机验证码发送
     * @param phone
     * @return
     */
    @PostMapping ("getcode/{phone}")
    public Result getcode(@PathVariable String phone) {
        System.out.println(phone);
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "64c02c9de9464bf3818a29877fb2d9d9";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105


        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content","code:"+uuid);
        bodys.put("phone_number",phone);
        bodys.put("template_id", "CST_ptdie100");

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());


            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (
                Exception e) {
            e.printStackTrace();
        }
        System.out.println(bodys.get("content"));
        String str = bodys.get("content");
        String result = str.substring(str.length() - 4);
        System.out.println(result);
        redisTemplate.opsForValue().set(phone,result,5, TimeUnit.MINUTES);
        return new Result(200,"验证码",bodys.get("content"));
    }

    /**
     * 校验验证码是否正确
     * @param number
     * @return
     */
    @PostMapping("inspectcode/{number}/{phone}")
    public Result inspectcode(@PathVariable String number,@PathVariable String phone){

        if (redisTemplate.hasKey(phone)){
            System.out.println(redisTemplate.opsForValue().get(phone));
            String code = redisTemplate.opsForValue().get(phone);
            if (number.equals(code)){
                System.out.println("验证成功");
                return new Result(200,"验证成功",true);
            }else {
                throw new BadCredentialsException("验证码错误");
            }
        }else {
            throw new BadCredentialsException("手机号不匹配");
        }
    }

    /**
     * 修改用户密码
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("changePassword/{phone}/{password}")
    public Result changePassword(@PathVariable String phone,@PathVariable String password){
        TGuest tGuest = tGuestService.selectByPhone(phone);
        tGuest.setGPassword(passwordEncoder.encode(password));
        Date date1 = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dateFormat.format(date1));
        Instant instant = date1.toInstant();
        LocalDate ld = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        tGuest.setUpdatetime(ld);
        tGuestService.updateById(tGuest);
        return new Result(200,"修改成功",true);
    }

    /**
     * 注册新用户
     * @param name
     * @param phone
     * @param sex
     * @param password
     * @return
     */

    @PostMapping("addguest/{name}/{phone}/{sex}/{password}")
    public Result addguest(@PathVariable String name,@PathVariable String phone,@PathVariable String sex,@PathVariable String password){
        TGuest tGuest =new TGuest();
        tGuest.setGName(name);
        tGuest.setGPhone(phone);
        tGuest.setSex(sex);
        tGuest.setGPassword(passwordEncoder.encode(password));
        tGuest.setGState(1);
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dateFormat.format(date));
        Instant instant = date.toInstant();
        LocalDate ld = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        tGuest.setUpdatetime(ld);
        tGuest.setCreatetime(ld);
        System.out.println(tGuest);
        tGuestService.save(tGuest);
        return new Result(200,"添加用户成功",true);
    }


    @PostMapping("getavatar/{phone}")
    public Result uploadImage(@PathVariable String phone,@RequestBody MultipartFile file){
        String imageUrl = ossClientUtil.checkImage(file);//获取url路径
        TGuest tGuest = tGuestService.selectByPhone(phone);
        tGuest.setAvatar(imageUrl);
        tGuestService.updateById(tGuest);
        return new Result(200,"添加图片成功",tGuest);
    }

}
